'use client';

import { useState } from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { formSend } from '@/utils';
import countries from './countries';

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string().email('Invalid email').required('Required'),
  company: Yup.string().required('Required'),
  country: Yup.string().required('Required'),
});

// import Select from 'react-select';
import {
  Button,
  LinearProgress,
  MenuItem,
  Fade,
  TextField,
  Snackbar,
  Autocomplete,
  Box,
} from '@mui/material';

// import { countries } from 'country-data';

const FormSection = () => {
  const [state, setState] = useState({
    open: false,
    Transition: Fade,
  });
  const [submitting, setSubmitting] = useState(false);
  const initialValues = {
    firstName: '',
    lastName: '',
    email: '',
    company: '',
    employees: '',
    country: '',
  };
  const formik = useFormik({
    initialValues,
    validationSchema: SignupSchema,
    onSubmit: async (values: any) => {
      setSubmitting(true);
      formSend('/api/mail/send', values);
      setTimeout(() => {
        setSubmitting(false);
        handleOpen();
        formik.resetForm();
      }, 2000);
    },
  });
  const handleOpen = () => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    setState({
      ...state,
      open: true,
    });
  };

  const handleClose = () => {
    setState({
      ...state,
      open: false,
    });
  };

  return (
    <>
      <iframe
        name="export_iframe"
        id="export_iframe"
        style={{
          position: 'absolute',
          width: 1,
          height: 1,
          left: '-1000px',
          opacity: 0,
        }}
      ></iframe>
      <Snackbar
        autoHideDuration={4000}
        //variant={'success'}
        open={state.open}
        onClose={handleClose}
        TransitionComponent={Fade}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        message="Your request has been sent successfully!"
      />
      <form onSubmit={formik.handleSubmit} id={'get-demo-form'}>
        <div className={'flex flex-col gap-6'}>
          <TextField
            fullWidth
            type="text"
            name="firstName"
            label={'First Name'}
            variant="outlined"
            value={formik.values.firstName}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.firstName && Boolean(formik.errors.firstName)}
            helperText={
              (!!formik.touched.firstName && formik.errors.firstName) as string
            }
          />
          <TextField
            fullWidth
            type="text"
            name="lastName"
            label={'Last Name'}
            variant="outlined"
            value={formik.values.lastName}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.lastName && Boolean(formik.errors.lastName)}
            helperText={
              (!!formik.touched.lastName && formik.errors.lastName) as string
            }
          />
          <TextField
            fullWidth
            type="email"
            name="email"
            label={'Business Email'}
            variant="outlined"
            value={formik.values.email}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.email && Boolean(formik.errors.email)}
            helperText={
              (!!formik.touched.email && formik.errors.email) as string
            }
          />
          <TextField
            fullWidth
            type="text"
            name="company"
            label={'Company'}
            variant="outlined"
            value={formik.values.company}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.company && Boolean(formik.errors.company)}
            helperText={
              (!!formik.touched.company && formik.errors.company) as string
            }
          />
          <TextField
            fullWidth
            type="text"
            name="employees"
            label={'Employees'}
            select
            variant="outlined"
            margin="normal"
            style={{ margin: 0 }}
            value={formik.values.employees}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.employees && Boolean(formik.errors.employees)}
            helperText={
              (!!formik.touched.employees && formik.errors.employees) as string
            }
          >
            {[
              { value: '1-50', label: '1-50' },
              { value: '51-100', label: '51-100' },
              { value: '100+', label: '100+' },
            ].map(option => (
              <MenuItem key={option.value} value={option.value}>
                {option.label}
              </MenuItem>
            ))}
          </TextField>

          <Autocomplete
            id="country-select-demo"
            fullWidth
            options={countries}
            autoHighlight
            onChange={(event, newValue) => {
              const input = document.getElementById(
                'country-select-demo'
              ) as HTMLInputElement;
              // @ts-ignore
              input.value = newValue?.label ?? '';
              formik.handleChange({
                ...event,
                currentTarget: input,
                target: input,
              });
            }}
            onInputChange={(event, newInputValue) => {
              const input = document.getElementById(
                'country-select-demo'
              ) as HTMLInputElement;
              formik.handleChange({
                ...event,
                currentTarget: input,
                target: input,
              });
            }}
            inputValue={formik.values.country}
            getOptionLabel={option => option.label}
            renderOption={(props, option) => {
              const { key, ...optionProps } = props;
              return (
                <Box
                  key={key}
                  component="li"
                  sx={{ '& > img': { mr: 2, flexShrink: 0 } }}
                  {...optionProps}
                >
                  <img
                    loading="lazy"
                    width="20"
                    srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                    src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                    alt=""
                  />
                  {option.label} ({option.code}) +{option.phone}
                </Box>
              );
            }}
            renderInput={params => (
              <TextField
                {...params}
                label="Choose a country"
                name={'country'}
                slotProps={{
                  htmlInput: {
                    ...params.inputProps,
                    autoComplete: 'new-password', // disable autocomplete and autofill
                  },
                }}
                // value={formik.values.country}
                style={{ margin: 0 }}
                onBlur={formik.handleBlur}
                error={formik.touched.country && Boolean(formik.errors.country)}
                helperText={
                  (!!formik.touched.country && formik.errors.country) as string
                }
              />
            )}
          />

          {/*<TextField*/}
          {/*  fullWidth*/}
          {/*  type="text"*/}
          {/*  name="country"*/}
          {/*  label={'Country'}*/}
          {/*  variant="outlined"*/}
          {/*  margin="normal"*/}
          {/*  style={{ margin: 0 }}*/}
          {/*  value={formik.values.country}*/}
          {/*  onChange={formik.handleChange}*/}
          {/*  onBlur={formik.handleBlur}*/}
          {/*  error={formik.touched.country && Boolean(formik.errors.country)}*/}
          {/*  helperText={*/}
          {/*    (!!formik.touched.country && formik.errors.country) as string*/}
          {/*  }*/}
          {/*/>*/}
          {submitting && <LinearProgress />}

          <Button
            size={'large'}
            fullWidth
            type={'submit'}
            variant="contained"
            color="primary"
            disabled={submitting}
          >
            <div className={'text-xl uppercase'}>Submit</div>
          </Button>
        </div>
      </form>
    </>
  );
};

const DemoPage = () => {
  return (
    <>
      <div className={'mx-auto max-w-4xl px-10 py-8'}>
        <h1
          className={
            'py-10 text-center font-sans text-3xl font-semibold uppercase'
          }
        >
          Request A Demo
        </h1>
        <FormSection />
      </div>
    </>
  );
};

export default DemoPage;
